package com.bey.bow.service.course;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.utils.DateProvider;

import com.bey.bow.entity.Course;
import com.bey.bow.entity.CourseDetail;
import com.bey.bow.repository.CourseDao;
import com.bey.bow.repository.CourseDetailDao;

//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class CourseService {

	private CourseDao courseDao;
	
	private CourseDetailDao courseDetailDao;

	private DateProvider dateProvider = DateProvider.DEFAULT;

	@Transactional(readOnly = false)
	public void saveCourse(Course entity) {
		entity.setCourseDate(dateProvider.getDate());
		courseDao.save(entity);
	}

	public Page<Course> getCourses(int pageNumber, int pageSize, String sortType) {

		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize,
				sortType);
		return courseDao.findAll(pageRequest);

	}

	public Course getCourse(Long id) {
		return courseDao.findOne(id);
	}
	
	@Transactional(readOnly = false)
	public void deleteCourse(Long id) {
		courseDao.delete(id);
	}
	
	@Transactional(readOnly = false)
	public void deleteCourseDetail(Long id, Long courseId) {
		Course course = courseDao.findOne(courseId);
		CourseDetail courseDetail = courseDetailDao.findOne(id);
		System.out.println(course.getCourseDetails().size());
		course.getCourseDetails().remove(courseDetail);
		System.out.println("after: " + course.getCourseDetails().size());
		courseDao.save(course);
		courseDetailDao.delete(id);
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize,
			String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("date".equals(sortType)) {
			sort = new Sort(Direction.DESC, "courseDate");
		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	@Autowired
	public void setCourseDao(CourseDao courseDao) {
		this.courseDao = courseDao;
	}

	@Autowired
	public void setCourseDetailDao(CourseDetailDao courseDetailDao) {
		this.courseDetailDao = courseDetailDao;
	}
	
	

}
